package com.sgb.kjwl.view.ui.activity.transport;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.google.gson.JsonObject;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.callback.ZMessageEvent;
import com.sgb.capital.model.PayInfoEntity;
import com.sgb.capital.view.ui.activity.PersonPayActivity;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.UrlConfig;
import com.sgb.kjwl.databinding.ActivityPayGoodsBinding;
import com.sgb.kjwl.di.transport.DaggerTransportComponent;
import com.sgb.kjwl.di.transport.TransportModule;
import com.sgb.kjwl.model.entity.CarInfo;
import com.sgb.kjwl.model.entity.GoodsOrderEntity;
import com.sgb.kjwl.model.entity.OrderEntity;
import com.sgb.kjwl.model.entity.self.GoodsSourceDetail;
import com.sgb.kjwl.model.entity.transport.SingleItemEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.utils.TextViewUtils;
import com.swgk.core.util.UiUtil;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.swgk.core.event.MenuEvent;
import com.sgb.kjwl.view.event.WebEvent;
import com.sgb.kjwl.view.ui.activity.WebActivity;
import com.sgb.kjwl.view.ui.activity.self.AddCarInfoActivity;
import com.sgb.kjwl.view.ui.activity.transport.owner.TransportOrderDetailOwnerActivity;
import com.sgb.kjwl.view.ui.adapter.transport.CargoCustomValueAdapter;
import com.sgb.kjwl.view.ui.adapter.transport.PayGoodsInfoAdapter;
import com.sgb.kjwl.view.widget.CarListPopWindow;
import com.sgb.kjwl.view.widget.ClearEditText;
import com.sgb.kjwl.view.widget.WrapLinearLayout;
import com.sgb.kjwl.view.widget.transport.AMapDialog;
import com.sgb.kjwl.viewmodel.transport.PayGoodsViewModel;
import com.sgb.link.entity.AMapAddressEntity;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

/**
 * @author: 王彬臣
 * @date: 2021/2/6
 * @Description: 货源-新接单
 */
public class PayGoodsOrderActivity extends AppActivity {
    ActivityPayGoodsBinding mBinding;
    @Inject
    PayGoodsViewModel mViewModel;
    //车辆选择
    private final List<CarInfo> mCarList = new ArrayList<>();
    private OptionsPickerView<CarInfo> mCarPicker;
    //货源no
    private String mSourceNo;
    //货源信息
    private List<SingleItemEntity> mGoodsList;
    private PayGoodsInfoAdapter mGoodsAdapter;
    //货车信息
    private List<SingleItemEntity> mCarInfoList;
    private PayGoodsInfoAdapter mCarInfoAdapter;
    //自定义字段列表
    private List<SingleItemEntity> mCustomList;
    private CargoCustomValueAdapter mCustomAdapter;
    GoodsSourceDetail goodsSourceDetail;
    GoodsOrderEntity mEntity = new GoodsOrderEntity();
    private static final int TO_GOODS_ORDER = 100;//跳转订单详情
    String orderNo;
    private CarInfo car;
    private int pos;
    private int Mark;//0.接单 1.询价接单
    private String carOfferNo;
    private OrderEntity mOrderEntity;
    CarListPopWindow carListPopWindow;

    public static void start(Context context, String no, GoodsSourceDetail goodsSourceDetail) {
        Intent intent = new Intent(context, PayGoodsOrderActivity.class);
        intent.putExtra(RouterKey.NO, no);
        intent.putExtra(RouterKey.STRING, goodsSourceDetail);
        context.startActivity(intent);
    }

    public static void start(Context context, String no, int mark) {
        Intent intent = new Intent(context, PayGoodsOrderActivity.class);
        intent.putExtra(RouterKey.NO, no);
        intent.putExtra(RouterKey.ID, mark);
        context.startActivity(intent);
    }

    public static void start(Context context, String no, int mark, String carOfferNo) {
        Intent intent = new Intent(context, PayGoodsOrderActivity.class);
        intent.putExtra(RouterKey.NO, no);
        intent.putExtra(RouterKey.ID, mark);
        intent.putExtra(RouterKey.CAROFFERNO, carOfferNo);
        context.startActivity(intent);
    }

    public static void start(Context context, int mark, OrderEntity entity) {
        Intent intent = new Intent(context, PayGoodsOrderActivity.class);
        intent.putExtra(RouterKey.ID, mark);
        intent.putExtra(RouterKey.DATA, (Serializable) entity);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerTransportComponent.builder()
                .appComponent(appComponent)
                .transportModule(new TransportModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initView() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_pay_goods);
        mBinding.setLifecycleOwner(this);
        Mark = getIntent().getIntExtra(RouterKey.ID, 0);

        carOfferNo = getIntent().getStringExtra(RouterKey.CAROFFERNO);
        mBinding.includeTitle.titleView.setText(Mark == 1 ? "确认接单" : "司机接单");
        mBinding.includeTitle.ivBack.setOnClickListener(v -> {
            finish();
        });
        mBinding.tvCargoOrdersSubmit.setOnClickListener(this::onMultiClick);
        mBinding.tvCargoOrdersProtocol.setText(Html.fromHtml("确认提交即表示您已阅读并同意"
                + "<font color='#5792FD'>《经营帮货物运输协议》</font>全部内容"));
        initRecycler();
        initEvent();
        initData();
    }

    private void initRecycler() {
        goodsSourceDetail = (GoodsSourceDetail) getIntent().getSerializableExtra(RouterKey.STRING);
        mSourceNo = getIntent().getStringExtra(RouterKey.NO);

        mEntity.setGoodsSourceNo(mSourceNo);
        mViewModel.getQuickBankList(this);
        //货源信息
        mGoodsList = new ArrayList<>();
        if (goodsSourceDetail != null) {
            mViewModel.syncGoodsInfo(mGoodsList, goodsSourceDetail);
            try {
                loadData(goodsSourceDetail);
            }catch (Exception e){

            }

        } else {
            if (Mark == 2 && mEntity != null) {
                mViewModel.getGoodsDetail(this, mOrderEntity.getGoodsSourceNo(), mGoodsList);
            } else {
                mViewModel.getGoodsDetail(this, mSourceNo, mGoodsList);
            }
        }
        mGoodsAdapter = new PayGoodsInfoAdapter(mGoodsList);
        mBinding.rvCargoOrdersGoods.setNestedScrollingEnabled(false);
        mBinding.rvCargoOrdersGoods.setLayoutManager(new LinearLayoutManager(this));
        mGoodsAdapter.bindToRecyclerView(mBinding.rvCargoOrdersGoods);
        //货车信息
        mCarInfoList = new ArrayList<>();

/*        mCarInfoAdapter = new PayGoodsInfoAdapter(mCarInfoList);
        mBinding.rvCargoOrdersCar.setNestedScrollingEnabled(false);
        mBinding.rvCargoOrdersCar.setLayoutManager(new LinearLayoutManager(this));
        mCarInfoAdapter.bindToRecyclerView(mBinding.rvCargoOrdersCar);*/
        //自定义字段列表
        mCustomList = new ArrayList<>();
        mCustomAdapter = new CargoCustomValueAdapter(mCustomList);
        mBinding.rvCargoOrdersField.setNestedScrollingEnabled(false);
        mBinding.rvCargoOrdersField.setLayoutManager(new LinearLayoutManager(this));
        DividerDecoration.builder(this)
                .colorRes(R.color.transparent)
                .size(10, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(mBinding.rvCargoOrdersField);
        mCustomAdapter.bindToRecyclerView(mBinding.rvCargoOrdersField);
    }

    private void initEvent() {
        mBinding.setOnClick(this);
        //自定义字段删除监听
        mCustomAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.iv_release_cargo_del) {
                mCustomList.remove(position);
                mCustomAdapter.notifyDataSetChanged();
                if (mCustomList.size() == 0) {
                    mBinding.rvCargoOrdersField.setVisibility(View.GONE);
                }
            }
        });
        carListPopWindow = new CarListPopWindow(this);
        carListPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                int pos = (int) key1;
                carSelect(pos);
            }
        });
        //接口回调
        mViewModel.ldCar.observe(this, carInfos -> {
            syncCarList(carInfos, false);
        });
        mViewModel.ldCarinfo.observe(this, carInfos -> {
            syncCarList(carInfos, true);
        });
        mViewModel.ldLocation.observe(this, this::syncLocation);
        mViewModel.ldDriverInfo.observe(this, driverInfo -> {
            mEntity.setContrcts(driverInfo.getName());
            mEntity.setContrctsNumber(driverInfo.getTelphone());
            // mViewModel.syncCarInfo(mCarInfoList, driverInfo);
            //  mCarInfoAdapter.notifyDataSetChanged();
        });
        mViewModel.ldTradeNo.observe(this, tradeNo -> {
            UiUtil.sendMsg(EventConstant.EVENT_REFRESH_GOODS, tradeNo.getOrderNo());
            orderNo = tradeNo.getOrderNo();
            if (TextUtils.isEmpty(orderNo)) {
                MToast.showToast(this, "未获取到订单号");
                return;
            }
            if (BigDecimal.ZERO.compareTo(BigDecimal.valueOf(tradeNo.getAmount())) == 0) {
                EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.EVENT_REFRESH_PAY_GOODS));
                ActivityJump.jumpToActivity(this, TransportOrderDetailOwnerActivity.class, Pair.create("no", orderNo),
                        Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.CAR_OWNER));
                finish();
                return;
            }
            PayInfoEntity paymentEntity = new PayInfoEntity();
            paymentEntity.amount = tradeNo.getAmount();
            // paymentEntity.tradeNo = tradeNo.getTradeNo();
            paymentEntity.orderId = tradeNo.getFreightOrderNo();
            PersonPayActivity.start(this, tradeNo.getFreightOrderNo());
            finish();

        });
        mViewModel.soureDetail.observe(this, goodsSourceDetail1 -> {
            try {
                loadData(goodsSourceDetail1);
            }catch (Exception e){

            }
        });
    }

    private void initData() {
        if (mEntity != null && Mark == 2) {
            setCarInfo();
            mViewModel.getDriverInfo();
        } else {
            //获取信息
            mViewModel.getCarInfo(this);
            mViewModel.getCurrentLocation(this);
        }
        mViewModel.getDriverInfo();
    }

    public void loadData(GoodsSourceDetail goodsSourceDetail) {
        this.goodsSourceDetail = goodsSourceDetail;
        if (Mark != 2) {
            mEntity.setAllFreight(goodsSourceDetail.getAllFreight());
            mEntity.setMessagePrice(goodsSourceDetail.getMessagePrice());
        }
        //货物信息
        List<String> strings = new ArrayList<>();
        if (!TextUtils.isEmpty(goodsSourceDetail.getGoodsTypesName())) {
            strings.add(goodsSourceDetail.getGoodsTypesName());
        }
        if (goodsSourceDetail.getFreightType()==null){
            if (!TextUtils.isEmpty(goodsSourceDetail.getFreight())) {
                strings.add(NumberUtil.trim0(goodsSourceDetail.getFreight()) + goodsSourceDetail.getFreightUnitType());
            }
        }else {
                if (goodsSourceDetail.getFreightType()==0&&!TextUtils.isEmpty(goodsSourceDetail.getFreight())){
                    strings.add(NumberUtil.trim0(goodsSourceDetail.getFreight()) + goodsSourceDetail.getFreightUnitType());
                }
        }

        if (!TextUtils.isEmpty(goodsSourceDetail.getWeight())) {
            strings.add(NumberUtil.trim0(goodsSourceDetail.getWeight()) + "吨");
        }
        if (!TextUtils.isEmpty(goodsSourceDetail.getVolume())) {
            strings.add(NumberUtil.trim0(goodsSourceDetail.getVolume()) + "方");
        }
        loadGoodsSourceInfo(strings, mBinding.goodsInfoLayout);

        if (goodsSourceDetail.getMessagePrice() != null) {
            mBinding.tvCargoOrdersPrice.setText(NumberUtil.trim0(goodsSourceDetail.getMessagePrice()) + "元");
        } else {
            mBinding.tvCargoOrdersPrice.setText("0元");
        }
        if (Mark == 0) {
            if (goodsSourceDetail.getFreightType() != null) {
                if (goodsSourceDetail.getFreightType() == 1) {
                    mBinding.tvCargoOrdersFreight.setText(String.format("运费核算：%s", "电议"));
                    mBinding.llPhoneFreight.setVisibility(View.VISIBLE);
                    mBinding.rlHint.setVisibility(View.VISIBLE);
                } else {
                    mBinding.tvCargoOrdersFreight.setText(String.format("运费核算：%s元", NumberUtil.trim0(goodsSourceDetail.getAllFreight())));
                }

            } else {
                mBinding.tvCargoOrdersFreight.setText(String.format("运费核算：%s元", NumberUtil.trim0(goodsSourceDetail.getAllFreight())));
            }
        } else {
            mBinding.tvCargoOrdersFreight.setText(String.format("运费核算：%s元", NumberUtil.trim0(goodsSourceDetail.getAllFreight())));
        }
    }

    /**
     * 装载货源信息
     */
    private void loadGoodsSourceInfo(List<String> strings, WrapLinearLayout lay_gallery) {
        lay_gallery.removeAllViews();
        LayoutInflater mInflater = LayoutInflater.from(getActivity());
        if (strings != null && strings.size() != 0) {
            for (int i = 0; i < strings.size(); i++) {
                final View view = mInflater.inflate(R.layout.item_goods_transport_info_02, lay_gallery, false);
                final TextView tv_info = view.findViewById(R.id.tv_info);
                tv_info.setText(strings.get(i));
                lay_gallery.addView(view);
            }
        }
    }

    /**
     * 初始化车辆选择器
     */
    private void syncCarList(List<CarInfo> list, boolean isReFresh) {
        mCarList.clear();
        if (list == null) return;
        mCarList.addAll(list);

        carListPopWindow.setData(list);

        if (!isReFresh) {
            //当只有一辆车时，填入默认值
            if (mCarList.size() == 1) {
                carSelect(0);
            }
        } else {
            carSelect(pos);
        }
    }


    /**
     * 车辆选择
     */
    private void carSelect(int index) {
        car = mCarList.get(index);
        StringBuilder strBuilder = new StringBuilder();
        if (!TextUtils.isEmpty(car.getCarNumber())) {
            strBuilder.append(car.getCarNumber());
        }
        if (!TextUtils.isEmpty(car.getCarTypeName())) {
            strBuilder.append(" ");
            strBuilder.append(car.getCarTypeName());
        }
        if (!TextUtils.isEmpty(car.getCarLenName())) {
            strBuilder.append(" ");
            strBuilder.append("长" + car.getCarLenName());
        }
        if (BigDecimal.ZERO.compareTo(BigDecimal.valueOf(car.getWeight())) != 0) {
            strBuilder.append(" ");
            strBuilder.append(NumberUtil.trim0(car.getWeight()) + "吨");
        }
        if (!TextUtils.isEmpty(car.getHeightHurdle())) {
            strBuilder.append(" ");
            strBuilder.append("栏高" + car.getHeightHurdle() + "米");
        }
        if (car.getIsDump() != null) {
            strBuilder.append(" ");
            if (car.getIsDump() == 0) {
                strBuilder.append("非自卸");
            } else if (car.getIsDump() == 1) {
                strBuilder.append("自卸");
            }
        }
        mBinding.tvCargoOrdersCar.setText(strBuilder.toString());
        mEntity.setCarNo(car.getNo());
        mEntity.setCarNumber(car.getCarNumber());
        if (car.getIsComplete() == 1) {
            mEntity.setCarLenNo(car.getCarLenNo());
            mEntity.setCarTypeNo(car.getCarTypeNo());
        }

    }

    /**
     * 同步定位信息
     */
    private void syncLocation(AMapAddressEntity entity) {
        if (entity == null) return;
        mBinding.tvCargoOrdersCarLocation.setText(String.format("%s%s%s",
                entity.getProvince(),
                entity.getCity(),
                entity.getDistrict()));
        mEntity.setLat(entity.getLatitude());
        mEntity.setLng(entity.getLongitude());
        mEntity.setProvinceName(entity.getProvince());
        mEntity.setCityName(entity.getCity());
        mEntity.setDistrictName(entity.getDistrict());
        mEntity.setProvinceNo(entity.getProvinceNo());
        mEntity.setCityNo(entity.getCityNo());
        mEntity.setDistrictNo(entity.getDistrictNo());
        mEntity.setDetailAddress(entity.getSnippet());
        mBinding.etCargoOrdersAddress.setVisibility(View.VISIBLE);
        mBinding.etCargoOrdersAddress.setText(DefaultUtil.getString(entity.getSnippet()));
        mBinding.line1.setVisibility(View.VISIBLE);
    }

    @Override
    public void onMultiClick(View v) {
        if (v == mBinding.includeTitle.ivBack) {
            finish();
        } else if (v == mBinding.tvCargoOrdersExpand) {
            if (mBinding.tvCargoOrdersExpand.isSelected()) {
                mBinding.rvCargoOrdersGoods.setVisibility(View.GONE);
                mBinding.tvCargoOrdersExpand.setText("展开更多");
                TextViewUtils.changeTextView(this, mBinding.tvCargoOrdersExpand, R.drawable.btn_shop_down, false);
            } else {
                mBinding.rvCargoOrdersGoods.setVisibility(View.VISIBLE);
                mBinding.tvCargoOrdersExpand.setText("收起更多");
                TextViewUtils.changeTextView(this, mBinding.tvCargoOrdersExpand, R.drawable.btn_shop_up, true);
            }
        } else if (v == mBinding.llCargoOrdersCar) {
            if (Mark == 2) return;
            if (carListPopWindow != null && mCarList.size() > 0) {
                carListPopWindow.showDownPopwindow(mBinding.llCargoOrdersCar, true);
                carListPopWindow.backgroundAlpha(0.5f);
            } else {
                MToast.showToast(this, "暂无数据");
            }
        } else if (v == mBinding.llCargoOrdersCarLocation) {
            if (Mark == 2) return;
            AMapDialog.launch(this);
        } else if (v == mBinding.tvCargoOrdersAdd) {
            addField();
        } else if (v == mBinding.tvCargoOrdersSubmit) {
            clearAllFocus();
            if (Mark == 0 && goodsSourceDetail.getFreightType() != null && goodsSourceDetail.getFreightType() == 1) {
                if (TextUtils.isEmpty(mBinding.tvPhoneFreight.getText().toString())) {
                    MToast.showToast(this, "请填写电议运费");
                    return;
                }
                int freight = NumberUtil.convertToInt(mBinding.tvPhoneFreight.getText().toString());
                if (freight < 10 || freight > 50000) {
                    MToast.showToast(this, "请输入10-50000内运费");
                    return;
                }
                mEntity.setAllFreight(mBinding.tvPhoneFreight.getText().toString());
            }
            String carInfo = mBinding.tvCargoOrdersCar.getText().toString();
            String location = mBinding.tvCargoOrdersCarLocation.getText().toString();
            String adress = mBinding.etCargoOrdersAddress.getText().toString();
            if (TextUtils.isEmpty(carInfo)) {
                new RoundDialog.Builder(this)
                        .title("提示")
                        .content("请选择车辆")
                        .cancel("暂不填写")
                        .singleBtn(true)
                        .contentGravity(Gravity.CENTER)
                        .show();
                return;
            }
            if (car != null && car.getIsComplete() == 0) {
                new RoundDialog.Builder(this)
                        .title("提示")
                        .content("请先完善" + car.getCarNumber() + "的车辆信息")
                        .cancel("暂不完善")
                        .confirm("确定").confirmCallback(view -> {
                    Intent intent = new Intent(this, AddCarInfoActivity.class);
                    intent.putExtra("carNo", Long.valueOf(car.getNo()));
                    startActivity(intent);
                }).show();
                return;
            }
            if (TextUtils.isEmpty(location)) {
                new RoundDialog.Builder(this)
                        .title("提示")
                        .content("请选择车辆位置")
                        .cancel("暂不填写")
                        .singleBtn(true)
                        .contentGravity(Gravity.CENTER)
                        .show();
                return;
            }
            if (TextUtils.isEmpty(adress)) {
                new RoundDialog.Builder(this)
                        .title("提示")
                        .content("请输入楼牌号")
                        .cancel("暂不填写")
                        .singleBtn(true)
                        .contentGravity(Gravity.CENTER)
                        .show();
                return;
            }
            if (!mBinding.cbCargoOrdersProtocol.isChecked()) {
                MToast.showToast(this, "请先勾选运输协议");
                return;
            }
            if (Mark == 0) {
                mViewModel.isFirstPay(this);
            } else {
                toPayOrder();
            }
        } else if (v == mBinding.tvCargoOrdersProtocol) {
            EventBus.getDefault().postSticky(WebEvent.make(EventConstant.EVENT_WEBVIEW, UrlConfig.NEW_BASE_URL + "logistics/operate/html/file/transportAgreement"));
            WebActivity.start(this);
        } else if (v == mBinding.ivRules) {
            showTextDialog(false);
        }
    }

    public void toPayOrder() {
        if (Mark != 2) {
            mEntity.setDetailAddress(mBinding.etCargoOrdersAddress.getText().toString());
        }
        if (!TextUtils.isEmpty(mBinding.etCargoQuotationMark.getText().toString())) {
            mEntity.setNote(mBinding.etCargoQuotationMark.getText().toString());
        }
        //新增字段json
        if (mCustomList != null && mCustomList.size() > 0) {
            JsonObject field = new JsonObject();
            for (SingleItemEntity diy : mCustomList) {
                field.addProperty(diy.getLeftString(), diy.getRightString());
            }
            mEntity.setAddField(field.toString());
        }
        if (Mark == 1) {
            mEntity.setCarOfferNo(carOfferNo);
            mEntity.setOrderStatus(1);
        } else {
            mEntity.setOrderStatus(0);
        }
        mEntity.setOrderStatus(Mark);
        if (Mark == 1) {
            mViewModel.getoperateInquiryOrderTaking(this, mEntity);
        } else {
            mViewModel.quotation(this, mEntity);
        }
    }

    /**
     * 添加更多字段
     */
    private void addField() {
        if (mCustomList.size() >= 3) {
            MToast.showToast(this, "最多添加3个字段");
            return;
        }
        mCustomList.add(new SingleItemEntity());
        mCustomAdapter.notifyDataSetChanged();
        if (mBinding.rvCargoOrdersField.getVisibility() == View.GONE) {
            mBinding.rvCargoOrdersField.setVisibility(View.VISIBLE);
        }
    }

    public void showTextDialog(boolean isShowBotton) {
        View view = View.inflate(getActivity(), R.layout.dialog_order_rules, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        TextView tv_sure = view.findViewById(R.id.tv_sure);
        ImageView img_cancel = view.findViewById(R.id.img_cancel);
        ConstraintLayout rl_content = view.findViewById(R.id.rl_content);
        if (isShowBotton) {
            tv_sure.setVisibility(View.VISIBLE);
            rl_content.setBackgroundResource(R.drawable.shape_circle_corner_white_half_5dp);
        }
        //确定
        tv_sure.setOnClickListener(v -> {
            if (isShowBotton) {
                toPayOrder();
            }
            roundCornerDialog.dismiss();
        });
        //取消
        img_cancel.setOnClickListener(v -> roundCornerDialog.dismiss());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        if (requestCode == TO_GOODS_ORDER) {//支付成功跳转订单详情
            UiUtil.sendMsg(EventConstant.EVENT_REFRESH_GOODS, null);
            EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.EVENT_REFRESH_PAY_GOODS));
            ActivityJump.jumpToActivity(this, TransportOrderDetailOwnerActivity.class, Pair.create("no", orderNo),
                    Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.CAR_OWNER));
            finish();
        } else {
            AMapAddressEntity entity = AMapDialog.get(data);
            if (entity != null) {
                mBinding.tvCargoOrdersCarLocation.setText(String.format("%s%s%s",
                        entity.getProvince(),
                        entity.getCity(),
                        entity.getDistrict()));
                mBinding.etCargoOrdersAddress.setVisibility(View.VISIBLE);
                mBinding.line1.setVisibility(View.VISIBLE);
                mBinding.etCargoOrdersAddress.setText(DefaultUtil.getString(entity.getSnippet()));
                //设置数据
                mEntity.setLat(entity.getLatitude());
                mEntity.setLng(entity.getLongitude());
                mEntity.setProvinceName(entity.getProvince());
                mEntity.setCityName(entity.getCity());
                mEntity.setDistrictName(entity.getDistrict());
                mEntity.setProvinceNo(entity.getProvinceNo());
                mEntity.setCityNo(entity.getCityNo());
                mEntity.setDistrictNo(entity.getDistrictNo());
                mEntity.setDetailAddress(entity.getSnippet());
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MenuEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_ORDER_FINISH) {
            finish();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LogisticsEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_CARINFO_COMMIT) {
            mCarList.get(pos).setIsComplete(1);
            car = mCarList.get(pos);
            mViewModel.getReFreshCarInfo(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReFresh(ZMessageEvent event) {
        if (event.code == Constants.EVENT_REFRESH) {//放弃支付运费关闭
            finish();
        }else if (event.code==Constants.EVENT_PAY_SUCCESS  ){
            finish();
        }else if (event.code==Constants.EVENT_REFRESH_ORDER){
            ActivityJump.jumpToActivity(this, TransportOrderDetailOwnerActivity.class, Pair.create("no", orderNo),
                    Pair.create("isGoodsOwner", TransportOrderDetailOwnerActivity.CAR_OWNER));
            finish();
        }

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void setCarInfo() {
        Glide.with(this).load(mOrderEntity.getCarImage()).into(mBinding.ivCargoOrdersCarImg);
        ClearEditText clearEditText = mBinding.etCargoOrdersAddress;
        clearEditText.setClearIcon(null);
        mBinding.etCargoOrdersAddress.setFocusable(false);
        mBinding.carIcon.setVisibility(View.GONE);
        mBinding.iconCarLocation.setVisibility(View.GONE);
        mBinding.tvCargoOrdersCar.setText(mOrderEntity.getCarNumber() + " " + (TextUtils.isEmpty(mOrderEntity.getCarType()) ? "" : mOrderEntity.getCarType()) + " " + (TextUtils.isEmpty(mOrderEntity.getCarLen()) ? "" : "长" + mOrderEntity.getCarLen()) + " " + (TextUtils.isEmpty(mOrderEntity.getWeight()) ? "" : mOrderEntity.getWeight() + " ") + (TextUtils.isEmpty(mOrderEntity.getHeightHurdle()) ? "" : "栏高" + mOrderEntity.getHeightHurdle() + "米") + " " + (TextUtils.isEmpty(mOrderEntity.getIsDump()) ? "" : mOrderEntity.getIsDump()));
        mBinding.etCargoOrdersAddress.setVisibility(View.VISIBLE);
        mBinding.etCargoOrdersAddress.setText(mOrderEntity.getDetailAddress());
        mBinding.tvCargoOrdersCarLocation.setText(mOrderEntity.getProvinceName() + "省" + mOrderEntity.getCityName() + "市" + mOrderEntity.getDistrictName() + "区");
    }
}
